package com.newbie.iSee;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.Bundle;
import android.util.Log;

import com.facebook.android.Facebook;

public class Facebook_interface {
	public Facebook mfacebook;
	public String accessToken;

	Facebook_interface(Facebook mfacebook) {
		this.mfacebook = mfacebook;
		this.accessToken = mfacebook.getAccessToken();
	}

	String getUID()// get user id
	{
		String uid = null;

		JSONTokener tokener = null;
		JSONObject o = null;

		// retrieve information from facebook
		try {
			tokener = new JSONTokener(mfacebook.request("me", new Bundle(),
					"GET"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// get uid from the returned json object
		try {
			o = (JSONObject) tokener.nextValue();
			uid = o.getString("id");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return uid;
	}

	String postComment(String pid, String message)// post a comment to pid and
													// return comment id
	{
		String cid = null;

		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost("https://graph.facebook.com/" + pid
				+ "/comments");

		MultipartEntity mpEntity = new MultipartEntity();
		ContentBody cbMessage = null;
		ContentBody cbAccessToken = null;
		try {
			cbMessage = new StringBody(message);
			cbAccessToken = new StringBody(accessToken);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mpEntity.addPart("access_token", cbAccessToken);
		mpEntity.addPart("message", cbMessage);

		httppost.setEntity(mpEntity);

		// DEBUG
		Log.d("test", "executing request :" + httppost.getRequestLine());

		// System.out.println( "executing request " + httppost.getRequestLine( )
		// );
		HttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpEntity resEntity = response.getEntity();

		JSONTokener tokener = null;
		JSONObject o = null;
		try {
			tokener = new JSONTokener(EntityUtils.toString(resEntity));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			o = (JSONObject) tokener.nextValue();
			cid = o.getString("id");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();

		return cid;
	}

	String uploadPhoto(String photoPath, String name, String aid)// upload photo
	{
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost("https://graph.facebook.com/" + aid
				+ "/photos");

		// File file = new File("/mnt/sdcard/DCIM/100MEDIA/IMAG0002.jpg");
		File file = new File(photoPath);
		// DEBUG
		Log.d("test", "FILE::" + file.exists()); // IT IS NOT NULL
		Log.d("test", "AT:" + accessToken); // I GOT SOME ACCESS TOKEN

		MultipartEntity mpEntity = new MultipartEntity();
		ContentBody cbFile = new FileBody(file, "image/jpeg");
		ContentBody cbMessage = null;
		ContentBody cbAccessToken = null;
		try {
			cbMessage = new StringBody(name);
			cbAccessToken = new StringBody(accessToken);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mpEntity.addPart("access_token", cbAccessToken);
		mpEntity.addPart("source", cbFile);
		mpEntity.addPart("message", cbMessage);

		httppost.setEntity(mpEntity);

		// DEBUG
		Log.d("test", "executing request :" + httppost.getRequestLine());

		// System.out.println( "executing request " + httppost.getRequestLine( )
		// );
		HttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpEntity resEntity = response.getEntity();

		// DEBUG
		// Log.d("test",response.toString());
		System.out.println(response.getStatusLine());
//		if (resEntity != null) {
//			try {
//				System.out.println(EntityUtils.toString(resEntity));
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		} // end if

		// get the pid
		JSONTokener tokener = null;
		try {
			tokener = new JSONTokener(EntityUtils.toString(resEntity));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject o = null;
		try {
			o = (JSONObject) tokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String pid = null;
		try {
			pid = o.getString("id");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();
		return pid;
	}

	String createAlbum(String name)// creat album with name and return the aid
	{
		String aid = null;

		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost("https://graph.facebook.com/me/albums");

		MultipartEntity mpEntity = new MultipartEntity();
		ContentBody cbMessage = null;
		ContentBody cbAccessToken = null;
		try {
			cbMessage = new StringBody(name);
			cbAccessToken = new StringBody(accessToken);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mpEntity.addPart("access_token", cbAccessToken);
		mpEntity.addPart("name", cbMessage);

		httppost.setEntity(mpEntity);

		// DEBUG
		Log.d("test", "executing request :" + httppost.getRequestLine());

		// System.out.println( "executing request " + httppost.getRequestLine( )
		// );
		HttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpEntity resEntity = response.getEntity();

		JSONTokener tokener = null;
		try {
			tokener = new JSONTokener(EntityUtils.toString(resEntity));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject o = null;
		try {
			o = (JSONObject) tokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			aid = o.getString("id");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();

		return aid;
	}

	PhotoInfo getPhotoInfo(String pid)// get pid s information
	{
		JSONTokener tokener = null;
		JSONObject o = null;
		Log.d("test"," "+pid);
		try {
			String tmp=mfacebook.request(pid, new Bundle(), "GET");
			Log.d("test","tmp "+tmp);
			tokener = new JSONTokener(tmp);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			o = (JSONObject) tokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String name = null;
		try {
			name = o.getString("name");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String time = null;
		try {
			time = o.getString("created_time");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String source = null;
		try {
			source = o.getString("source");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String picture = null;
		try {
			picture = o.getString("picture");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String from = null;
		String fromName = null;
		try {
			from = o.getJSONObject("from").getString("id");
			fromName = o.getJSONObject("from").getString("name");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		JSONArray JsonA = null;
		Comment[] comments = null;
		if (o.isNull("comments") != true) {

			try {
				JsonA = o.getJSONObject("comments").getJSONArray("data");
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			comments = new Comment[JsonA.length()];
			for (int i = 0; i < JsonA.length(); i++) {
				String CMfrom = null;
				String CMmessage = null;
				String CMtime = null;
				try {
					JSONObject json = JsonA.getJSONObject(i);
					CMfrom = json.getJSONObject("from").getString("name");
					CMmessage = json.getString("message");
					CMtime = json.getString("created_time");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				comments[i] = new Comment(CMfrom, CMmessage, CMtime);
			}
		}
		return new PhotoInfo(name, from, fromName, time, picture, source, pid, comments);
	}

	Friend[] getFriend(String uid)// get the uid 's all friend
	{
		JSONTokener tokener = null;
		JSONObject o = null;
		JSONArray JsonA = null;
		Log.d("taco","get friend uid"+uid);
		try {
			tokener = new JSONTokener(mfacebook.request(uid + "/friends",
					new Bundle(), "GET"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			o = (JSONObject) tokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			JsonA = o.getJSONArray("data");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Friend[] friends = new Friend[JsonA.length()];
		for (int i = 0; i < JsonA.length(); i++) {
			String fname = null;
			String fid = null;
			try {
				JSONObject json = JsonA.getJSONObject(i);
				fname = json.getString("name");
				fid = json.getString("id");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			friends[i] = new Friend(fid, fname);
		}
		return friends;
	}

	String getName(String uid)// get the uid name
	{
		String name = null;
		JSONTokener tokener = null;
		JSONObject o = null;
		try {
			tokener = new JSONTokener(mfacebook.request(uid, new Bundle(),
					"GET"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			o = (JSONObject) tokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			name = o.getString("name");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return name;
	}

	String[] getAllAlbum(String uid)// get all album id belong to the uid
	{
		JSONTokener tokener = null;
		JSONObject o = null;
		JSONArray JsonA = null;
		try {
			tokener = new JSONTokener(mfacebook.request(uid + "/albums",
					new Bundle(), "GET"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			o = (JSONObject) tokener.nextValue();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			JsonA = o.getJSONArray("data");
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String[] aids = new String[JsonA.length()];
		for (int i = 0; i < JsonA.length(); i++) {
			try {
				JSONObject json = JsonA.getJSONObject(i);
				aids[i] = json.getString("id");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return aids;
	}

	PhotoInfo[] getAlbumInfo(String aid)// get all photoInfo in album aid
	{
		PhotoInfo[] photos = null;

		JSONTokener tokener = null;
		JSONObject o = null;
		JSONArray JsonA = null;
		try {
			tokener = new JSONTokener(mfacebook.request(aid + "/photos",
					new Bundle(), "GET"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			o = (JSONObject) tokener.nextValue();
			JsonA = o.getJSONArray("data");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		photos = new PhotoInfo[JsonA.length()];
		for (int j = 0; j < JsonA.length(); j++) {
			JSONObject o1 = null;
			String name = null;
			String time = null;
			String source = null;
			String picture = null;
			String from = null;
			String fromName = null;
			String pid = null;
			try {
				o1 = JsonA.getJSONObject(j);
				name = o1.getString("name");
				time = o1.getString("created_time");
				source = o1.getString("source");
				picture = o1.getString("picture");
				from = o1.getJSONObject("from").getString("id");
				fromName = o1.getJSONObject("from").getString("name");
				pid = o1.getString("id");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			JSONArray JsonA1 = null;
			Comment[] comments = null;
			if (o1.isNull("comments") != true) {

				try {
					JsonA1 = o1.getJSONObject("comments").getJSONArray("data");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				comments = new Comment[JsonA1.length()];
				for (int i = 0; i < JsonA1.length(); i++) {
					String CMfrom = null;
					String CMmessage = null;
					String CMtime = null;
					try {
						JSONObject json = JsonA1.getJSONObject(i);
						CMfrom = json.getJSONObject("from").getString("name");
						CMmessage = json.getString("message");
						CMtime = json.getString("created_time");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					comments[i] = new Comment(CMfrom, CMmessage, CMtime);
				}
			}
			photos[j] = new PhotoInfo(name, from, fromName, time, picture, source, pid,
					comments);
		}
		return photos;
	}
}

class PhotoInfo // if photo no comment CMlist could be null
{
	String name;// photo describe
	String from;// Photo owner id
	String fromName;// Photo owner's name
	String time;
	String picture; // small one
	String source; // big one
	String pid;
	Comment[] CMlist;

	PhotoInfo(String name, String from, String fromName, String time, String picture,
			String source, String pid, Comment[] CMlist) {
		this.name = name;
		this.from = from;
		this.fromName = fromName;
		this.time = time;
		this.picture = picture;
		this.source = source;
		this.pid = pid;
		this.CMlist = CMlist;
	}
}

class Comment {
	String from;
	String message;
	String time;

	public Comment(String from, String message, String time) {
		this.from = from;
		this.message = message;
		this.time = time;
	}
}

class Friend {
	String uid;
	String name;

	public Friend(String uid, String name) {
		this.uid = uid;
		this.name = name;
	}
}
